import { LoginLog } from './../entitys/LoginLog';
import { Context } from 'koa';
import { Service } from "typedi";
import * as parser from "ua-parser-js"
import { getConnection, getRepository } from 'typeorm';
import { User } from '../entitys/User';
import Page from '../common/page';
import axios from "axios"
import * as moment from 'moment';
import { YYYY_MM_DD_HH_MM_SS } from '../utils/utils';
@Service()
export class LoginLogService {
    async save(ctx: Context, user: User) {
        const req: any = ctx.req
        var ip = req.headers['x-forwarded-for'] ||
            req.ip ||
            req.connection.remoteAddress ||
            req.socket.remoteAddress ||
            req.connection.socket.remoteAddress || '';
        if (ip.split(',').length > 0) {
            ip = ip.split(',')[0]
        }

        ip = ip.substr(ip.lastIndexOf(':') + 1, ip.length);

        const ua = parser(ctx.headers['user-agent'])
        const repository = getRepository(LoginLog)
        const loginLog = new LoginLog()
        loginLog.loginTime = new Date()
        loginLog.os = ua.os.name + "/" + ua.os.version
        loginLog.ua = ua.ua
        loginLog.userId = user.id
        loginLog.browser = ua.browser.name + "/" + ua.browser.version
        const url = `http://opendata.baidu.com/api.php?query=${ip}&co=&resource_id=6006&oe=utf8`
        console.log(url)
        axios.get(url).then((res) => {
            loginLog.ip = ip
            loginLog.location = res.data.data[0].location
            console.log(res.data.data)
            repository.save(loginLog)
        })

    }
    async getLoginLogList({ pageNum = 1, pageSize = 10 }: { pageNum?: number, pageSize?: number } = {}) {
        const repository = getRepository(LoginLog)
        const queryBuilder = repository.createQueryBuilder("loginLog")
        queryBuilder.leftJoinAndSelect(User, "user", "user.id = loginLog.userId")
            .select(["loginLog.id as id", 'loginLog.os as os', 'loginLog.browser as browser', 'loginLog.ip as ip', 'loginLog.location as location', 'loginLog.ua as ua', 'loginLog.loginTime as loginTime', 'loginLog.userId as userId', 'user.username as username', 'user.nickname as nickname'])
        const count = await queryBuilder.getCount()
        const page = new Page(count, pageNum, pageSize);
        const result = await queryBuilder.orderBy('loginLog.loginTime', 'DESC').offset(page.startIndex).limit(page.pageSize).getRawMany()
        result.forEach(d => {
            d.loginTime = moment(d.loginTime).format(YYYY_MM_DD_HH_MM_SS)
        })
        page.list = result
        return page
    }
}